<template>
	<view class="container" ref="scrollView">
		<view class="aititle">
			<image src="@/static/images/ai/ai-title.png"></image>
		</view>
		<view v-for="(item,index) in speakList" :key="index">
			<view class="reportbox" v-if="item.showType == 'report'">
				<view class="banner">
					AI智能解读报告
				</view>
				<view class="textbox">
					<view class="text">
						<rich-text :nodes="item.value"></rich-text>
					</view>
					<view class="footer">
						该解读报告由AI生成，仅供参考
					</view>
				</view>
			</view>
			<view class="speakbox clearfix" v-if="item.showType == 'person'">
				<view class="personSpeak" v-html="item.value">
				</view>
			</view>
			<view v-if="item.showType == 'ai'">
				<view class="speakbox clearfix" v-if="index == speakList.length-1 && !isloading">
					<view class="aiSpeak" v-html="item.value"></view>
				</view>
				<view class="speakbox clearfix" v-if="index != speakList.length-1">
					<view class="aiSpeak" v-html="item.value"></view>
				</view>
			</view>
			
			
		</view>
		<view class="speakbox clearfix" v-if="isloading">
			<view class="aiSpeak loading">
				正在思考，请稍等...
			</view>
		</view>
		<view class="stop" v-if="stopSpeak" @click="stopSpeaking()">
			<image src="@/static/images/ai/stop.png"></image>
			停止回答
		</view>
		
		<view class="search-footer">
			<view class="search-area">
				<image src="@/static/images/ai/voice-icon.png"></image>
				<input class="input" type="text" v-model="searchValue" />
				<button :loading="isSpeaking" :disabled="isSpeaking" :class="!searchValue?'disabled':''" class="button" @click="personSpeak()">
				 	<text v-if="!isSpeaking">发送</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import config from "@/config.js";
	import { fetchEventSource } from '@microsoft/fetch-event-source';
	import { getDeepseek,getDeepseek2 } from "@/api/home/home.js";
	export default {
		data() {
			return {
				thinkLock:false,
				interval:'',
				isloading: false,
				isSpeaking: false,
				stopSpeak: false,
				searchValue: '',
				speakList:[],
				eventSource:'',
				content:'',
			}
		},
		components:{},
		onLoad(option){
			if(option.content){
				var dictCode = option.dictCode || '00';
				this.content = this.decodeFromBase64(option.content);
				if(dictCode == '01'){
					this.speakList.push({
						showType:'person',
						value: '报告解读',
					})
				}
				this.isSpeaking = true;
				setTimeout(()=>{
					this.isloading = true;
				},200)
				this.searchDeepseek(this.content,'report',dictCode);
			}
		},
		mounted() {
			this.eventSource = new AbortController();
		},
		methods: {
			// 解码base64
			decodeFromBase64(value) {
				return decodeURIComponent(atob(value));
			},
			personSpeak(){
				if(!this.searchValue){
					this.$msg("你没有输入内容哦！");
					return
				}
				this.isSpeaking = true;
				this.isloading = true;
				// ai person report,
				var searchValue = JSON.parse(JSON.stringify(this.searchValue))
				this.speakList.push({
					showType:'person',
					value: searchValue,
				})
				this.scrollToBottom();
				this.searchDeepseek(this.content + " " + searchValue,'ai','00');
				this.searchValue = '';
			},
			searchDeepseek(searchValue, showType, dictCode) {
			  var that = this;
			  let cnt = searchValue;
			  cnt = cnt.replace(/\>+/g, "大于");
			  cnt = cnt.replace(/\＜+/g, "小于");
			  // dictCode: dictCode,
			  var params = {
			    stream: true,
			    model: "QYSRMYY",
			    messages: [{"role":"user","content":cnt}],
			  };
		
			  this.speakList.push({ showType: showType, value: ""});
			  var content = "<think class='think'>";
			  var vI = this.speakList.length - 1;
			  fetchEventSource('https://zsyy.hnsqysrmyy.cn/v1/sendNetBook', {
				method: 'POST',
				headers: {
				  'Authorization': '',
				  'Content-Type': 'application/json', // 文本返回格式
				},
				body: JSON.stringify(params),
				signal: that.eventSource.signal,
				openWhenHidden: true, // 在浏览器标签页隐藏时保持与服务器的EventSource连接
				onmessage(res) {
				  // 操作流式数据
				  let a = res.data.includes("DONE");
				  if (a) {
					// 关闭流
					that.stopSpeaking();
				  } else {
					var msgObj = '';
					console.log('JSON.parse(res.data)===',JSON.parse(res.data))
					if(JSON.parse(res.data).choices){
					 //  let thinkE = res.data.includes("think");
					 //  if(thinkE){
						// that.thinkLock = true;
						// that.stopSpeak = true;
						// that.isloading = false;
					 //  }
					  that.thinkLock = true;
					  that.stopSpeak = true;
					  that.isloading = false;
					  if(that.thinkLock){
						msgObj = JSON.parse(res.data).choices[0].delta.content;
					  }
					}
					content += msgObj;
					let result = content;
					// 移除#号和*号
					result = result.replace(/[#*]/g, '');
					result = result.replace(/\n\n/g, "");
					result = result.replace(/\n/g, "<br/>");
					
					that.$set(that.speakList[vI], "value", result);
					if (result.length % 18 == 0) {
					  that.scrollToBottom();
					}
				  }
				},
				onclose(res) {
				  // 关闭流 
				  that.stopSpeaking();
				},
				onerror(error) {
				  // 返回流报错
				  console.error("返回流报错--SSE Error:", error);
				  that.stopSpeaking();
				  throw error
				}
			  })
			},
			// 关闭流
			stopSpeaking() {
			  this.isSpeaking = false;
			  this.isloading = false;
			  this.stopSpeak = false;
			  this.thinkLock = false;
			  this.eventSource.abort();
			},
			typeWriter(text, speed) {
				this.stopSpeak = true;
				var vI = this.speakList.length - 1;
			    var textContent = '';
			    let i = 0; // 初始化字符索引
				var that = this;
				if(this.interval){
					clearInterval(that.interval);
				}
			    this.interval = setInterval(function() {
			        if (i < text.length) {
			            textContent += text.charAt(i);
						that.$set(that.speakList[vI],'value',textContent);
			            i++;
			        } else {
						that.isSpeaking = false;
						that.stopSpeak = false;
			            clearInterval(that.interval); // 完成打字后清除定时器
			        }
					if(i%18 == 0){
						that.scrollToBottom()
					}
			    }, speed?speed:100); // 速度，单位毫秒
			},		
			scrollToBottom() {
			  this.$nextTick(() => {
				const scrollView = this.$refs.scrollView.$el;
				console.log('scrollView.scrollHeight==',scrollView.scrollHeight)
				scrollView.scrollTop = scrollView.scrollHeight; // 设置scrollTop为scrollHeight，滚动到底部
			  });
			}
		},
		beforeDestroy() {
			this.eventSource.abort();
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 12px 16px;
		width: 100%;
		height: 100vh;
		overflow-y: auto;
		background-image: url('@/static/images/ai/ai-box-bg.png');
		background-size: 100% 100%;
		padding-bottom: 100px;
	}
	.aititle {
		image {
			height: 75px;
			width: 100%;
		}
	}

	.reportbox {
		margin-top: 16px;

		.banner {
			width: 100%;
			height: 75px;
			font-size: 20px;
			font-weight: 600;
			padding: 12px 16px;
			box-sizing: border-box;
			background-image: url('@/static/images/ai/report-title.png');
			background-size: 100% 100%;
		}

		.textbox {
			width: 100%;
			margin-top: -16px;
			padding: 16px;
			box-sizing: border-box;
			background: #fff;
			border-radius: 10px;

			.text {
				font-size: 16px;
				color: #313C56;
			}

			.footer {
				border-top: 1px solid #E6E8F2;
				padding-top: 12px;
				margin-top: 16px;
				font-size: 12px;
				color: #ccc;
			}
		}
	}

	.speakbox {
		width: 100%;
		margin-top: 16px;
	}

	.personSpeak,
	.aiSpeak {
		color: #fff;
		font-size: 16px;
		padding: 15px;
		border-radius: 15px 3px 15px 15px;
		background: #3F81F1;
		display: inline-block;
		max-width: 90%;
		float: right;
	}
	
	.aiSpeak {
		color: #313C56;
		background: #fff;
		border-radius: 3px 15px 15px 15px;
		float: left;
		.loading{color: #909090;}
		
	}
	::v-deep{
		.think{color: #aaa!important;}
	}
	.stop{
		width: 90px;
		height: 38px;
		line-height: 38px;
		text-align: center;
		border-radius: 28px;
		background: #FFFFFF;
		margin: 16px auto;
		image{
			vertical-align: middle;
			width: 12px;
			height: 12px;
			margin-right: 4px;
		}
	}
	.search-footer{
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		padding: 16px;
		max-height: 120px;
		overflow: auto;
		background-image: url('@/static/images/ai/ai-box-bg.png');
		background-size: cover;
		.search-area{
			width: 100%;
			min-height: 46px;
			border-radius: 25px;
			background: #FFFFFF;
			border: 1px solid #E4E6E8;
			position: relative;
			image{
				width: 24px;
				height: 24px;
				display: inline-block;
				margin: 10px 10px 0 10px;
			}
			.input{
				width: 65%;
				height: 32px;
				vertical-align: bottom;
				display: inline-block;
			}
			.button{
				display: inline-block;
				height: 28px;
				width: 50px;
				padding: 0px;
				font-size: 14px;
				float: right;
				margin: 10px 10px 0 0;
				line-height: 28px;
				text-align: center;
				border-radius: 14px;
				background: #3F81F1;
				color: #fff;
				
			}
			.disabled{
				background: rgba(63, 129, 241 ,0.3);
			}
		}
	}
	
	.clearfix::after {
		content: "";
		display: table;
		clear: both;
	}
	
	#moveObj{ width: 100px; height: 120px; background-color: yellow; position: absolute; left: 50px;top:0;}
</style>